package com.fyk.service.Impl;

import com.fyk.entity.User;
import com.fyk.mapper.UserMapper;
import com.fyk.mapper.UserRoleMapper;
import com.fyk.service.UserService;
import com.fyk.utils.ResultUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author qazws
 * @Date 2022/8/19 17:28
 * @Version 1.0
 */

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserRoleMapper userRoleMapper;


    @Override
    public ResultUtils login(User user) {
        if (user.getUsername() == "" || user.getPassword() == ""){
            return new ResultUtils(500,"用户名或密码不能为空！",null);
        }

        try {
            Subject subject = SecurityUtils.getSubject();

            UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(),user.getPassword());

            subject.login(token);
            subject.getSession().setAttribute("user",userMapper.selectUserByUsername(user.getUsername()));
        }catch (UnknownAccountException e){
            return new ResultUtils(500,"用户名不存在",null);
        }catch (IncorrectCredentialsException e){
            return new ResultUtils(500,"密码错误",null);
        }
        Map<String,Object> map = new HashMap<>();
        map.put("role",userRoleMapper.selectRoleByUsername(user.getUsername()));

        return new ResultUtils(200,"登录成功",map);
    }

    @Override
    public ResultUtils updateUser(User user) {
        userMapper.updateUser(user);
        return new ResultUtils(200,"修改成功！",null);
    }

    @Override
    public ResultUtils findUser() {
        Subject subject = SecurityUtils.getSubject();
        User user = (User) subject.getSession().getAttribute("user");
        Integer userId = user.getUserId();
        return new ResultUtils(200,null,userMapper.selectUserByUserId(userId));
    }

    @Override
    public ResultUtils insertUser(User user) {
        if (userMapper.selectUserByUsername(user.getUsername()) != null){
            return new ResultUtils(500,"用户名名重复",null);
        }
        user.setDeleted(0);
        user.setJoinData(new Date());
        userMapper.insertUser(user);
        Integer userId = userMapper.selectUserByUsername(user.getUsername()).getUserId();
        userRoleMapper.insertUserAndRole(userId,2);
        return new ResultUtils(200,"注册成功！",null);
    }

    @Override
    public ResultUtils outUser() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return new ResultUtils(200,"退出成功",null);
    }
}
